//
//  MainViewController.m
//  小碗旅行
//
//  Created by wyzcWLB on 16/9/26.
//  Copyright © 2016年 wyzcWLB. All rights reserved.
//

#import "MainViewController.h"
#import "Btn.h"
#import "LeftViewController.h"
#import <AFNetworking.h>
#import <SVProgressHUD.h>
#import "slideModel.h"
#import <UIImageView+WebCache.h>
#import "footTableViewModel.h"
#import "footTableViewCell.h"
#import "ClickViewController.h"
#import <MJRefresh.h>

#define Screen_Width [UIScreen mainScreen].bounds.size.width
#define Screen_Height [UIScreen mainScreen].bounds.size.height

@interface MainViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>

@property(nonatomic,strong)UIScrollView *ad;
@property(nonatomic,strong)NSMutableArray *adArray;
@property(nonatomic,strong)UIImageView *imageView;
@property(nonatomic,strong)UIView *btnView;
@property(nonatomic,strong)UIPageControl *pagecontrol;
@property(nonatomic,strong)NSTimer *timer;
@property(nonatomic,strong)NSArray *icon;

@property(nonatomic,strong)UITableView *tabelView;
@property(nonatomic,strong)NSMutableArray *footArray;
@end

@implementation MainViewController
-(NSMutableArray *)adArray{
    if (!_adArray) {
        _adArray = [NSMutableArray array];
    }
    return _adArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"topnav"]forBarMetrics:UIBarMetricsDefault];
    
    
    [self loadData];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    

    [self addloadData];
    
    [self creatFootView];
    
}

-(void)loadData{

    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *url = @"http://open.qyer.com/qyer/recommands/entry?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&lat=40.03623104039519&lon=116.3638251674019&page=1&track_app_channel=App%2520Store&track_app_version=6.8&track_device_info=iPhone7%2C1&track_deviceid=7B6FA080-F9FB-44C1-B932-401CD69CD5D2&track_os=ios%25209.1&v=1";
    //请求数据
    [manager GET:url parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray *slide = responseObject[@"data"][@"slide"];
       // NSLog(@"%@",slide);
        for (NSDictionary *dict in slide) {
            slideModel *model = [slideModel slideWithDict:dict];
            [self.adArray addObject:model];
        }if(self.adArray)
        {
            [self addHeaderScorllView];
            [self addbutton];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //请求失败的指示器
        [SVProgressHUD showErrorWithStatus:@"网路错误"];
        NSLog(@"%@",error);
    }];
}

#pragma mark 加载ScorllView
-(void)addHeaderScorllView{
    
    self.ad= [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, Screen_Width, Screen_Height*0.25)];
    [self.view addSubview:_ad];
    
    //代理
    self.ad.delegate = self;
    
    self.pagecontrol = [[UIPageControl alloc]initWithFrame:CGRectMake(Screen_Width-100, 34+Screen_Height*0.25, 80, 20)];
    [self.view addSubview:_pagecontrol];


    for (int i=0; i<self.adArray.count; i++) {
        slideModel *model = self.adArray[i];
        //NSLog(@"%@",model);
        UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(Screen_Width*i, 0, Screen_Width, Screen_Height*0.25)];
        //给每个图片设置一个tag值，点击跳转url
        imgView.tag = i;
        
        [imgView sd_setImageWithURL:[NSURL URLWithString:model.photo]];
        
        //把imageView添加到scrollView
        [self.ad addSubview:imgView];
        
        
        // 1. 创建一个点击事件，点击时触发labelClick方法
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickImg:)];
        [imgView addGestureRecognizer:tap];
        imgView.userInteractionEnabled = YES;

    }
    
    //如果想实现scrollView里面内容的滚动 就必须设置contentSize
    self.ad.contentSize = CGSizeMake(self.adArray.count*self.ad.frame.size.width, 0);
    self.ad.showsHorizontalScrollIndicator = NO;
    //pagingEnabled 可以实现自动分页
    self.ad.pagingEnabled = YES;
    //总页数
    self.pagecontrol.numberOfPages = self.adArray.count;
    //设置其它小圆点的颜色
    self.pagecontrol.pageIndicatorTintColor=[UIColor whiteColor];
    //当前小圆点的颜色
    self.pagecontrol.currentPageIndicatorTintColor=[UIColor redColor];
    //添加定时器
    _timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(scrollViewPicture) userInfo:nil repeats:YES];
    
    
    //获取最大Y 值
    CGFloat y=CGRectGetMaxY(self.ad.frame);
    self.btnView = [[UIView alloc]initWithFrame:CGRectMake(0, y, Screen_Width, Screen_Height*0.125+5
                                                           )];
    //设置背景图片
    _btnView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"PayOnlineBackgroudImg"]];
    [self.view addSubview:_btnView];
    
}

-(void)clickImg:(UITapGestureRecognizer *)imageView{
   
    ClickViewController *click = [[ClickViewController alloc]init];
    click.num = imageView.view.tag;
    click.adArray = self.adArray;
    [self presentModalViewController:click animated:YES];
}

//开始拖拽会调用该方法
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    //关闭定时器  定时器对象就会销毁
    [_timer invalidate];
    _timer = nil;
}

//当结束拖拽后 在重新建立定时器
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(scrollViewPicture) userInfo:nil repeats:YES];
    
}

-(void)scrollViewPicture{
    //获取当前页数
    NSInteger num = _pagecontrol.currentPage;
    if (num == self.adArray.count-1) {
        num = 0;
    }else{
        num++;
    }
    //重新给pageControl的当前页赋值
    self.pagecontrol.currentPage = num;
    //要想实现偏移 就要告诉scrollView的contentOffset的偏移量
    self.ad.contentOffset = CGPointMake(num*self.ad.frame.size.width, 0);
}

//监听scrollView正在滚动
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    //获取scrollView在X轴上的偏移量  因为scrollView每偏移一个图片宽度pagecontrol的当前页就要更换
    CGFloat w = self.ad.contentOffset.x;
    int num = w/self.ad.frame.size.width;
    //当前页跟谁scrollView偏移的距离来更换
    self.pagecontrol.currentPage = num;
}

#pragma mark 添加按钮
-(void)addbutton{
    
    CGFloat width = self.btnView.bounds.size.width/5.0;
    CGFloat y = self.btnView.bounds.origin.y+self.btnView.bounds.size.height*0.2;
    CGFloat height = self.btnView.bounds.size.height*0.5;
   
    //既有文字又有图片，重写layoutSubviews方法修改UIbutton控件内部布局
    Btn *btn1 = [[Btn alloc]initWithFrame:CGRectMake(width, y, width, height)];
    [btn1 setImage:[UIImage imageNamed:@"btn_poi_ent_on"] forState:UIControlStateNormal];
    [btn1 setTitle:@"看锦囊" forState:UIControlStateNormal];
    [btn1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_btnView addSubview:btn1];
    [btn1 addTarget:self action:@selector(jump) forControlEvents:UIControlEventTouchUpInside];
    
    
    Btn *btn2 = [[Btn alloc]initWithFrame:CGRectMake(width*3, y, width, height)];
    [btn2 setImage:[UIImage imageNamed:@"btn_poi_shopping_on"] forState:UIControlStateNormal];
    [btn2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn2 setTitle:@"抢折扣" forState:UIControlStateNormal];
    [_btnView addSubview:btn2];
}

-(void)jump{
    
    LeftViewController *left = [[LeftViewController alloc]init];
   
    //隐藏tabBar标签栏，一定在跳转之前隐藏
    left.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:left animated:YES];
    
}

-(void)creatFootView{
    _tabelView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64+Screen_Height*0.375+5, Screen_Width, Screen_Height*0.625-64-49)];
   // _tabelView.backgroundColor = [UIColor redColor];
    
    _tabelView.delegate = self;
    _tabelView.dataSource = self;
    //隐藏滚动条
    self.tabelView.showsVerticalScrollIndicator = NO;
    
    [self.view addSubview:_tabelView];

}
-(NSMutableArray *)footArray{
    if (!_footArray) {
        _footArray = [NSMutableArray array];
    }
    return _footArray;
}
#pragma mark 加载数据
-(void)addloadData{
    
    //请求管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *url = @"http://open.qyer.com/qyer/recommands/trip?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=10&lat=40.03623104039519&lon=116.3638251674019&page=1&track_app_channel=App%2520Store&track_app_version=6.8&track_device_info=iPhone7%2C1&track_deviceid=7B6FA080-F9FB-44C1-B932-401CD69CD5D2&track_os=ios%25209.1&type=index&v=1";
    //请求数据
    [manager GET:url parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray *data = responseObject[@"data"];
        for (NSDictionary *dict in data) {
            footTableViewModel *model = [footTableViewModel footTableViewModelWithDict:dict];
            [self.footArray addObject:model];
            
        }

        //NSLog(@"%@",_footArray);
        
        [_tabelView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //请求失败的指示器
        [SVProgressHUD showErrorWithStatus:@"网路错误"];
        NSLog(@"%@",error);
    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.footArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *ID = @"abc";
    
    footTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell==nil) {
        cell = [footTableViewCell loadfootTableViewCell];

    }
    
    footTableViewModel *model = self.footArray[indexPath.row];
    
    [cell.photo sd_setImageWithURL:[NSURL URLWithString:model.photo]];
    cell.photo.layer.cornerRadius = 5;
    cell.photo.layer.masksToBounds = YES;
    cell.username.text = model.username;
    cell.title.text = model.title;
    cell.backgroundColor = [UIColor lightGrayColor];
    return cell;
}

//监听选中哪行
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    footTableViewModel *model = self.footArray[indexPath.row];
    
    NSURL *url = [NSURL URLWithString:model.view_url];
    
    [[UIApplication sharedApplication]openURL:url];
//    [self presentModalViewController:footView animated:YES];
    

}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 170;
}

@end
